import datetime

from src.formats.MapServiceManager import mapServiceManager
from src.formats.RedisData import RedisCache


# 全局变量
# mapServiceManager = MapServiceManager.mapServiceManager
redisCache = RedisCache()

def GetTileFromSLRC(servicename, level, row, column):
    key = mapServiceManager.serviceList[servicename]['config']['type'] + '_' + servicename + '_' + str(
        level) + '_' + str(row) + '_' + str(column)
    tile = redisCache.getBinaryData(key)
    if tile is None:
        try:
            if mapServiceManager.serviceList[servicename]['config']['type'] == 'mbt':
                tile = mapServiceManager.serviceList[servicename]['tilesManager'].getTileFromLRC(level, row, column,
                                                                                                 mapServiceManager.serviceList[
                                                                                                     servicename]['config']['tileSize'])
            elif mapServiceManager.serviceList[servicename]['config']['type'] == 'bundle':
                tile = mapServiceManager.serviceList[servicename]['tilesManager'].getTileFromLRC(level, row, column)
            else:
                tile = mapServiceManager.serviceList[servicename]['tilesManager'].getTileFromLRC(level, row, column)
            redisCache.setBinaryData(key, tile['imgData'])
        except:
            raise Exception
    else:
        tile = {
            "level": level,
            "row": row,
            "column": column,
            "imgData": tile
        }
    return tile

# 三维区域
def GetSlpkJson(servicename):
    return mapServiceManager.serviceList[servicename]['tilesManager'].getJson()


def GetSlpkRootJson(servicename):
    return mapServiceManager.serviceList[servicename]['tilesManager'].getRootJson()


def GetSlpkNodeJson(servicename, tilename):
    return mapServiceManager.serviceList[servicename]['tilesManager'].getNodeJson(tilename)


def GetSlpkSublayersJson(servicename, tilename):
    return mapServiceManager.serviceList[servicename]['tilesManager'].getSublayersJson(tilename)


def GetSlpkNodeSharedJson(servicename, tilename):
    return mapServiceManager.serviceList[servicename]['tilesManager'].getNodeSharedJson(tilename)


def GetSlpkNodepages(servicename, filename):
    key = mapServiceManager.serviceList[servicename]['config']['type'] + '_' + servicename + '_nodepages_' + filename

    file = redisCache.getBinaryData(key)

    if file is None:
        try:
            file = mapServiceManager.serviceList[servicename]['tilesManager'].getNodepages(filename)
        except:
            raise Exception

        redisCache.setBinaryData(key, file)

    return file


def GetSlpkGeometries(servicename, tilename, filename):
    key = mapServiceManager.serviceList[servicename]['config'][
              'type'] + '_' + servicename + '_nodes_' + tilename + '_geometries_' + filename

    file = redisCache.getBinaryData(key)

    if file is None:
        try:
            file = mapServiceManager.serviceList[servicename]['tilesManager'].getGeometries(tilename, filename)
        except:
            raise Exception

        redisCache.setBinaryData(key, file)

    return file


def GetSlpkTextures(servicename, tilename, filename):
    key = mapServiceManager.serviceList[servicename]['config'][
              'type'] + '_' + servicename + '_nodes_' + tilename + '_textures_' + filename

    file = redisCache.getBinaryData(key)

    if file is None:
        try:
            file = mapServiceManager.serviceList[servicename]['tilesManager'].getGetTextures(tilename, filename)
        except:
            raise Exception

        redisCache.setBinaryData(key, file)

    return file


def GetSlpk_path(servicename, full_path):
    path, para_num = division(full_path)
    # print(path)
    key = mapServiceManager.serviceList[servicename]['config']['type']
    for path_name in path:
        key = key + '_' + path_name
    # print(key)
    file = redisCache.getBinaryData(key)

    if file is None:
        try:
            file = mapServiceManager.serviceList[servicename]['tilesManager'].getslpks_path(full_path)
        except:
            raise Exception

        redisCache.setBinaryData(key, file)

    return file


# 获取包内指定路径的数据
# 首先请求redis缓存，若无将调用瓦片管理对象上的获取包内文件的方法
#     如果获取到了将返回并保存到redis中，否则将报错
def GetSlpkFile(servicename, full_path, fileName, file_ext):
    path, para_num = division(full_path)
    key = mapServiceManager.serviceList[servicename]['config']['type'] + '_' + servicename
    for path_name in path:
        key = key + '_' + path_name
    file, ziptype, mimetype = redisCache.getSlpkData(key)

    # file = redisCache.getBinaryData(key)

    if file is None:
        try:
            start = datetime.datetime.now()
            file, ziptype, mimetype = mapServiceManager.serviceList[servicename]['tilesManager'].getFile(full_path,fileName,file_ext)
            end = datetime.datetime.now()
            print('no redis Running time: %s Seconds' % (end - start))
        except:
            raise Exception

        # redisCache.setBinaryData(key, file)
        redisCache.setSlpkData(key, file, ziptype, mimetype)
    start = datetime.datetime.now()
    end = datetime.datetime.now()
    print('redis Running time: %s Seconds' % (end - start))
    return file, ziptype, mimetype


def GetZipFile(servicename, full_path, fileName, file_ext):
    path, para_num = division(full_path)
    key = mapServiceManager.serviceList[servicename]['config']['type'] + '_' + servicename
    for path_name in path:
        key = key + '_' + path_name
    file, ziptype, mimetype = redisCache.getSlpkData(key)

    if file is None:
        try:
            start = datetime.datetime.now()

            file, ziptype, mimetype = mapServiceManager.serviceList[servicename]['tilesManager'].getFile(full_path,
                                                                                                         fileName,
                                                                                                         file_ext)
            end = datetime.datetime.now()
            print('no redis Running time: %s Seconds' % (end - start))
        except:
            raise Exception

        # redisCache.setBinaryData(key, file)
        redisCache.setSlpkData(key, file, ziptype, mimetype)
    start = datetime.datetime.now()
    end = datetime.datetime.now()
    print('redis Running time: %s Seconds' % (end - start))
    return file, ziptype, mimetype


def division(full_path):
    path = full_path.split('/')
    para_num = len(path)
    return path, para_num


def Get3DTilesJson(servicename, filename):
    return mapServiceManager.serviceList[servicename]['tilesManager'].getJson(filename)


def Get3DTilesFiles(servicename, tilename, filename):
    key = mapServiceManager.serviceList[servicename]['config'][
              'type'] + '_' + servicename + '_' + tilename + '_' + filename
    fFormat = filename.split('.')[1]

    file = ''
    if fFormat == 'b3dm':
        file = redisCache.getBinaryData(key)

        if file is None:
            try:
                file = mapServiceManager.serviceList[servicename]['tilesManager'].getTileFile(tilename, filename)
            except:
                raise Exception

            redisCache.setBinaryData(key, file)

    elif fFormat == 'json':
        file = redisCache.getTextData(key)

        if file is None:
            try:
                file = mapServiceManager.serviceList[servicename]['tilesManager'].getTileFile(tilename, filename)
            except:
                raise Exception

            redisCache.setTextData(key, file)
    else:
        file = mapServiceManager.serviceList[servicename]['tilesManager'].getTileFile(tilename, filename)

    return file


def Get3DTilesFiles_f1(servicename, folder1, folder2, filename):
    key = mapServiceManager.serviceList[servicename]['config'][
              'type'] + '_' + servicename + '_' + folder1 + '_' + folder2 + '_' + filename
    fFormat = filename.split('.')[1]

    file = ''
    if fFormat == 'b3dm':
        file = redisCache.getBinaryData(key)

        if file is None:
            try:
                file = mapServiceManager.serviceList[servicename]['tilesManager'].getFile_fromRoot(
                    folder1 + '/' + folder2, filename)
            except:
                raise Exception

            redisCache.setBinaryData(key, file)

    elif fFormat == 'json':
        file = redisCache.getTextData(key)

        if file is None:
            try:
                file = mapServiceManager.serviceList[servicename]['tilesManager'].getFile_fromRoot(
                    folder1 + '/' + folder2, filename)
            except:
                raise Exception

            redisCache.setTextData(key, file)
    else:
        file = mapServiceManager.serviceList[servicename]['tilesManager'].getFile_fromRoot(folder1 + '/' + folder2,
                                                                                           filename)

    return file
